package com.goldcn.user.service;

import com.goldcn.config.TokenConstants;
import com.goldcn.jwt.JWTSigner;
import com.goldcn.user.dto.LoginDto;
import com.goldcn.user.model.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * redis服务
 * Created by Administrator on 2016/3/1.
 */

@Service
@Transactional
@ConfigurationProperties(prefix = "spring.redis")
public class RedisService {

    private static JWTSigner signer = new JWTSigner();
    private Integer expire;
    private Integer expireRas;
    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    UserLoginService userLoginService;

    /**
     * token缓存并保存用户登录信息
     */
    public String addOrUpdate(UserInfo user, LoginDto loginDto, List<String> funCodeList) {

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userId", user.getUserID());
        map.put("userName", loginDto.getLoginName());
        map.put("funCodeList", funCodeList);
        String token = signer.sign(map);
        redisTemplate.opsForValue().set(user.getUserID().toString(), token);
        //缓存不超过1周
        if (loginDto.getExpireDate() > 0 && loginDto.getExpireDate() < 8) {
            int seconds = 86400 * loginDto.getExpireDate();
            redisTemplate.expire(user.getUserID(), seconds, TimeUnit.SECONDS);
        } else
            redisTemplate.expire(user.getUserID(), expire, TimeUnit.SECONDS);
        return token;
    }

    public String saveToken(Map<String,Object> map,Long userID){
        String token = signer.sign(map);
        String  k = new StringBuffer().append(TokenConstants.preTk).append(userID).toString();
        set(k,token,60L);
        return (String) loadKey(k);
    }

    public String getToken(Long userID){
        String  k = new StringBuffer().append(TokenConstants.preTk).append(userID).toString();
        return (String) loadKey(k);
    }

    public String saveToken(Map<String,Object> map,String k){
        String token = signer.sign(map);
        set(k,token,60L);
        return (String) loadKey(k);
    }

    public String getToken(String k){
        return (String) loadKey(k);
    }

  /*  public void set(){
        redisTemplate.opsForValue().set("9-NM0TXGTZmjyt6frmjC0A","eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOiI5LU5NMFRYR1RabWp5dDZmcm1qQzBBIiwidXNlck5hbWUiOiIxMzMxNjU4ODY4NyJ9./8Xjupyd284vH/DN/KrYkzEaULhrndfW36DRXBJUcvA=");
    }*/

    public void set(String k, Object v,Long timeout) {
        redisTemplate.opsForValue().set(k, v,timeout,TimeUnit.SECONDS);
    }

    public void setTimeOut(String k,Long expire){
        redisTemplate.expire(k, expire, TimeUnit.SECONDS);
    }

    public Object loadKey(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    public void delete(String userId) {
        redisTemplate.delete(userId);
    }


    /**
     * RAS私钥
     */
    public void addOrUpdateRAS(String rasID, Object privateKey) {
        redisTemplate.opsForValue().set(rasID, privateKey);
        redisTemplate.expire(rasID, expireRas, TimeUnit.SECONDS);
    }

    public void setExpire(Integer expire) {
        this.expire = expire;
    }

    public void setExpireRas(Integer expireRas) {
        this.expireRas = expireRas;
    }

    public boolean incr(String k) {
        Long count = redisTemplate.opsForValue().increment(k, 1);
        if (count == 1) {
            //设置有效期12s
            redisTemplate.expire(k, 12, TimeUnit.SECONDS);
        }
        if (count > 1) {
            return false;
        }
        return true;
    }

    public Long incr(String k,Long delta) {
        Long count = redisTemplate.opsForValue().increment(k, delta);
        return count;
    }

    public Long getIncrVal(String k){
        return incr(k,0L);
    }
}
